﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using ServiceKit.Aop;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace ServiceKit.Extensions
{
    public static class AopExtensions
    {
        private static string key = "ValidedAopService";

        public static bool IsValidedAopService(this Type interfaceType, IMemoryCache cache)
        {
            List<string> logger = new List<string>();
            if (interfaceType.IsInterface && typeof(IService).IsAssignableFrom(interfaceType))
            {
                bool paramflag = true;
                bool returnflag = true;
                var methods = interfaceType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
                foreach (var method in methods)
                {
                    var methodParams = method.GetParameters();
                    foreach (var methodParam in methodParams)
                    {
                        var methodparamflag = methodParam.ParameterType.BaseType.IsGenericType && methodParam.ParameterType.BaseType.GetGenericTypeDefinition() == typeof(AopRequest<>);
                        if (!methodparamflag)
                        {
                            logger.Add(interfaceType.Name + "服务的" + method.Name + "方法" + methodParam.Name + "参数没有继承AopRequest");
                        }
                        paramflag = paramflag && methodparamflag;
                    }
                    var methodreturnflag = method.ReturnType.BaseType == typeof(AopResponse);
                    if (!methodreturnflag)
                    {
                        logger.Add(interfaceType.Name + "服务的" + method.Name + "方法的返回参数没有继承AopResponse");
                    }
                    returnflag = returnflag && methodreturnflag;
                }
                if (!(paramflag && returnflag))
                {
                    logger.Add(interfaceType.Name + "服务验证不通过,不可访问!");
                }
            }
            cache.Set(key, logger);
            return true;
        }
    }
}
